import React, { Component } from 'react';
import { Card, Button, Modal } from 'antd';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';

export default class Rich extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contentState: '',   // 富文本内容
      editorState: '',  // 富文本状态
      showRichText: false,  // 显示弹框
    }
  }

  render() {
    const { editorState, contentState, showRichText } = this.state;
    return (
      <div>
        <Card className="pinlor-cards pinlor-buttons">
          <Button type="primary" onClick={this.handleClearContent}>清空内容</Button>
          <Button type="primary" onClick={this.handleGetText}>获取html文本</Button>
        </Card>
        <Card title="富文本编辑器">
          <Editor
            editorState={editorState}
            onContentStateChange={this.onEditorChange}
            onEditorStateChange={this.onEditorStateChange}
          />
        </Card>
        <Modal
          title="富文本"
          visible={showRichText}
          footer={null}
          onCancel={this.handleCancel}>
          {contentState}
        </Modal>
      </div>
    )
  }

  onEditorChange = contentState => {
    // 编辑时的富文本内容
    this.setState({
      contentState: draftToHtml(contentState)
    })
  };

  onEditorStateChange = (editorState) => {
    // 编辑时的富文本状态
    this.setState({
      editorState
    })
  };

  handleClearContent = () => {
    // 清空
    this.setState({
      editorState: ''
    })
  };

  handleGetText = () => {
    // 获取html文本
    this.setState({
      showRichText: true,
      editorState: ''
    })
  };

  handleCancel = () => {
    this.setState({
      showRichText: false
    })
  }
}

